<template>
  <div>
                <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-row>
            <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-row>

        <!-- 角色列表区域 -->
        <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- prop表示渲染数据源的某个属性 ,label表示该列的名称-->
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- row代表一行el-col将整个区域分成24个列-->
            <el-row v-for="(item,i1) in scope.row.children" :key="item.id" :class="['bdbottom',i1===0?'bdtop':'','vcenter']">
              <!-- 一级权限 -->
             <el-col :span="5">
              <el-tag closable @close="removeRolesId(scope.row,item.id)">{{item.authName}}</el-tag>
               <i class="el-icon-caret-right"></i>
             </el-col>
             <!-- 二级和三级权限 -->
             <el-col :span="19">
               <!-- for循环 嵌套循环二三级权限 -->
               <el-row  v-for="(item2,i2) in item.children" :key="item2.id" :class="[i2===0?'':'bdtop','vcenter']">
                 <el-col :span="6">
                   <el-tag closable type="success" @close="removeRolesId(scope.row,item2.id)">{{item2.authName}}</el-tag>
                   <i class="el-icon-caret-right"></i>
                 </el-col>
                 <!-- 三级循环 -->
                 <el-col :span="18" class="vcenter">
                       <el-tag type="warning" v-for="item3 in item2.children" closable
                       @close="removeRolesId(scope.row,item3.id)"
                       :key="item3.id">{{item3.authName}}</el-tag>
                 </el-col>
               </el-row>
             </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column  label="操作">
          <template slot-scope="scope">
           <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row.id)">编辑</el-button>
           <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row.id)">删除</el-button>
           <el-button type="warning" icon="el-icon-setting" size="mini" @click="getRightDialog(scope.row)">设置权限</el-button>
          </template>
        </el-table-column>
         </el-table>
    </el-card>
    <!-- 编辑用户对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="60%"
    @close="editCloseDialog">
      <el-form
        :model="editRolesForm"
        ref="editRolesRef"
        label-width="70px"
      >
        <el-form-item label="角色名称">
          <el-input v-model.trim="editRolesForm.roleName"></el-input>
        </el-form-item>
      <el-form-item label="角色描述">
          <el-input v-model.trim="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户对话框 -->
     <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="60%"
     @close="addCloseDialog">
      <el-form
        :model="addRolesForm"
        ref="addRolesRef"
        label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model.trim="addRolesForm.roleName"></el-input>
        </el-form-item>
      <el-form-item label="角色描述">
          <el-input v-model.trim="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
  title="提示"
  :visible.sync="showSetRightDialog"
  width="30%"
  >
<!-- 树形控件 -->
<el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
:default-checked-keys="treeKeyIds" ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showSetRightDialog = false">取 消</el-button>
    <el-button type="primary" @click="SetRightDialog">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
     data() {
         return {
             roleList:[],
             rightsList:[],//所有权限的数据
             editDialogVisible:false,//修改用户对话框
             editRolesForm:{},//查询,修改角色信息
             addDialogVisible:false,//添加用户对话框
             showSetRightDialog:false,//分配权限对话框
             addRolesForm:{
                 roleName:"",
                 roleDesc:""
             },
            //  树形控件的属性绑定对象
            treeProps:{
              label:'authName',
              children:'children'
            },
            // 默认选中的节点key的数组
            treeKeyIds:[],
            // 分配角色前对应的id值
            roleId:'',
         }
     },
     created(){
         this.getRoleList()
     },
     methods:{
        //  开始加载角色
        async getRoleList(){
           const {data,}=await this.$http.get('roles')
                if(data.meta.status!==200){return this.$message.error('角色加载失败')}
                console.log(data);
                this.roleList=data.data
         },
             //监听修改角色对话框的关闭
          editCloseDialog(){
          this.$refs.editRolesRef.resetFields();
       },
            //   监听添加用户对话框的关闭
         addCloseDialog(){
             this.$refs.addRolesRef.resetFields();
             this.addRolesForm.roleName='';
             this.addRolesForm.roleDesc='';
         },
        //  修改用户前查询角色
       async editRoles(id){
            const {data,}=await this.$http.get(`roles/${id}`)
            if (data.meta.status !== 200) {
               return this.$message.error("获取角色信息失败");
             }
            this.editRolesForm=data.data;
            this.editDialogVisible=true
        },
        // 提交编辑角色
       async editRolesInfo(){
           console.log(this.editRolesForm.roleId);
           const { data } = await this.$http.put(`roles/${this.editRolesForm.roleId}`, {
          roleName:this.editRolesForm.roleName,roleDesc:this.editRolesForm.roleDesc
        });
        console.log(data);
        if (data.meta.status !== 200) {
          this.$message.error(data.meta.msg);
        } else {
          this.$message.success("修改角色成功");
        }
        //隐藏用户对话框
        this.editDialogVisible = false;
        // 重新获取用户列表
        this.getRoleList(); 
        },
        // 删除角色
        async removeRoles(id){
            // 弹框确认用户是否删除
     const confirmResult=await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        ;
        // 用户确认删除
        // 用户确认删除，返回值是confirm
        // 取消返回值是cancel
        if(confirmResult!=='confirm'){
          return this.$message.info('已取消删除')
        }
        // 用户确认删除，发送请求删除该数据
        const {data}=await this.$http.delete(`roles/${id}`)
        console.log(data);
        if(data.meta.status!==200) return this.$message.error(data.meta.msg)
         this.$message.success('删除成功')
         this.getRoleList()
        },
        // 添加角色
       async addRolesInfo(){
            this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) {
          this.addDialogVisible = false;
          return this.$message.error("信息错误");
        }
        const { data } = await this.$http.post("roles", this.addRolesForm);
        console.log(data);
        if (data.meta.status !== 201) {
          this.$message.error(data.meta.msg);
        } else {
          this.$message.success("添加用户成功");
        }
        //隐藏用户对话框
        this.addDialogVisible = false;
        // 重新获取用户列表
        this.getRoleList();
        },)},
        // 删除权限功能
      async  removeRolesId(role,rightId){
             // 弹框确认用户是否删除
     const confirmResult=await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        ;
        // 用户确认删除
        // 用户确认删除，返回值是confirm
        // 取消返回值是cancel
        if(confirmResult!=='confirm'){
          return this.$message.info('已取消删除')
        }
        // 用户确认删除，发送请求删除该数据
        const {data}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        console.log(data);
        if(data.meta.status!==200) return this.$message.error(data.meta.msg)
         this.$message.success('删除成功')
        //  通过实参将循环的数据源获得，可以进行修改
         role.children=data.data
        },
        // 显示分配权限功能对话框
       async getRightDialog(role){
         this.roleId=role.id
          // 获取所有权限
        const {data,}= await this.$http.get('rights/tree')
        if(data.meta.status!==200){return this.$message.error('获取权限数据失败')} 
           this.rightsList=data.data;
          //  获取当前角色下所有的权限
          this.treeKeyIds=[];
           this.getLeafKeys(role,this.treeKeyIds);
          //  console.log(role.children);

          //  console.log(this.treeKeyIds);
          this.showSetRightDialog=true;
        },
        // 分配权限功能
       async SetRightDialog(){
            const keys=[...this.$refs.treeRef.getHalfCheckedKeys(),
            ...this.$refs.treeRef.getCheckedKeys()];
            const keysStr=keys.toString();
          let rolesId=window.Number(this.roleId);
         const {data,}=await this.$http.post(`roles/${rolesId}/rights`,{rids:keysStr})
         if(data.meta.status!==200){
           return this.$message.error(this.data.msg)
         };
         this.$message.success('添加权限成功')
         this.getRoleList();
         this.showSetRightDialog=false;

        },
        // 通过递归的形式获得所有角色三级权限id保存到treeKeyIds中
        getLeafKeys(node,arr){
         if(!node.children){
           //  如果是三级节点就把id值存入数组中
           return arr.push(node.id)
         };
         node.children.forEach(value => {
            this.getLeafKeys(value,arr)
         });
        },
            
}}
</script>

<style lang="less" scoped>
.el-button{
    margin-right: 10px;
}
.el-tag{
  margin: 15px 8px 8px 8px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
